<template>
  <div class="teacher-attendance-manage">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ $t('attendance.manage') }}</span>
      </div>
      
      <el-form :inline="true" :model="queryForm" class="demo-form-inline">
        <el-form-item :label="$t('course.title')">
          <el-select v-model="selectedCourse" :placeholder="$t('common.pleaseSelect') + ' ' + $t('course.title')" @change="handleCourseChange">
            <el-option
              v-for="course in teacherCourses"
              :key="course.id"
              :label="course.name"
              :value="course">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div class="operation-bar" v-if="selectedCourse">
        <el-button type="primary" @click="handleBatchAttendance">{{ $t('attendance.batch') }}</el-button>
        <el-button type="success" @click="handleManualRecord">{{ $t('attendance.manual') }}</el-button>
      </div>

      <el-table
        v-if="selectedCourse"
        :data="studentList"
        style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" :label="$t('user.id')"></el-table-column>
        <el-table-column prop="name" :label="$t('user.name')"></el-table-column>
        <el-table-column :label="$t('attendance.todayStatus')">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.todayStatus)">
              {{ getStatusText(scope.row.todayStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('common.operation')" v-if="!isMobile">
          <template slot-scope="scope">
            <el-button type="text" @click="recordSingle(scope.row)">{{ $t('attendance.recordAttendance') }}</el-button>
          </template>
        </el-table-column>
        <!-- 移动端操作列 -->
        <el-table-column :label="$t('common.operation')" width="95" fixed="right" v-if="isMobile">
          <template slot-scope="scope">
            <el-popover
              placement="left"
              width="120"
              trigger="click">
              <div class="mobile-operation-buttons">
                <el-button type="text" @click="recordSingle(scope.row)">{{ $t('attendance.recordAttendance') }}</el-button>
              </div>
              <el-button slot="reference" type="primary" size="mini">
                {{ $t('common.operation') }} <i class="el-icon-arrow-down"></i>
              </el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 批量考勤对话框 -->
    <el-dialog :title="$t('attendance.batch')" :visible.sync="batchDialogVisible" width="500px" :fullscreen="isMobile">
      <el-form :model="batchForm" label-width="100px">
        <el-form-item :label="$t('attendance.status')">
          <el-select v-model="batchForm.status" :placeholder="$t('common.pleaseSelect') + ' ' + $t('attendance.status')">
            <el-option :label="$t('attendance.normal')" :value="0"></el-option>
            <el-option :label="$t('attendance.late')" :value="1"></el-option>
            <el-option :label="$t('attendance.earlyLeave')" :value="2"></el-option>
            <el-option :label="$t('attendance.absent')" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('common.remark')">
          <el-input type="textarea" v-model="batchForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="batchDialogVisible = false">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="submitBatchAttendance">{{ $t('common.confirm') }}</el-button>
      </div>
    </el-dialog>

    <!-- 手动记录对话框 -->
    <el-dialog :title="$t('attendance.manual')" :visible.sync="manualDialogVisible" width="500px" :fullscreen="isMobile">
      <el-form :model="manualForm" label-width="100px">
        <el-form-item :label="$t('user.student')">
          <el-select v-model="manualForm.userId" :placeholder="$t('common.pleaseSelect') + ' ' + $t('user.student')">
            <el-option
              v-for="student in studentList"
              :key="student.id"
              :label="student.name"
              :value="student.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('attendance.status')">
          <el-select v-model="manualForm.status" :placeholder="$t('common.pleaseSelect') + ' ' + $t('attendance.status')">
            <el-option :label="$t('attendance.normal')" :value="0"></el-option>
            <el-option :label="$t('attendance.late')" :value="1"></el-option>
            <el-option :label="$t('attendance.earlyLeave')" :value="2"></el-option>
            <el-option :label="$t('attendance.absent')" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('common.remark')">
          <el-input type="textarea" v-model="manualForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="manualDialogVisible = false">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="submitManualRecord">{{ $t('common.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import request from '@/utils/request'

export default {
  name: 'TeacherAttendanceManage',
  data() {
    return {
      queryForm: {},
      teacherCourses: [],
      selectedCourse: null,
      studentList: [],
      selectedStudents: [],
      batchDialogVisible: false,
      manualDialogVisible: false,
      batchForm: {
        status: null,
        remark: ''
      },
      manualForm: {
        userId: null,
        status: null,
        remark: ''
      },
      isMobile: false,
      screenWidth: document.body.clientWidth
    }
  },
  computed: {
    userId() {
      return getUserId()
    }
  },
  created() {
    this.getTeacherCourses()
    this.checkScreenSize()
  },
  mounted() {
    window.addEventListener('resize', this.handleResize)
    this.checkScreenSize()
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    handleResize() {
      this.screenWidth = document.body.clientWidth
      this.checkScreenSize()
    },
    checkScreenSize() {
      this.isMobile = this.screenWidth < 768
    },
    async getTeacherCourses() {
      try {
        const userId = this.userId
        if (!userId) {
          this.$message.error('未获取到用户ID，请重新登录')
          return
        }
        
        const res = await request.get(`/course/teacher/${userId}`)
        
        if (res.code === 200) {
          this.teacherCourses = res.data || []
        } else {
          this.$message.error(res.msg || '获取课程列表失败')
        }
      } catch (error) {
        console.error('获取课程列表失败:', error)
        this.$message.error('获取课程列表失败')
      }
    },
    async handleCourseChange(course) {
      if (course) {
        try {
          const res = await request.get(`/course/${course.id}/students`)
          
          if (res.code === 200) {
            this.studentList = (res.data || []).map(student => ({
              ...student,
              todayStatus: null // 这里可以调用接口获取今日考勤状态
            }))
            
            // 获取今日考勤状态
            await this.getTodayAttendanceStatus(course.id)
          } else {
            this.$message.error(res.msg || '获取学生列表失败')
            this.studentList = []
          }
        } catch (error) {
          console.error('获取学生列表失败:', error)
          this.$message.error('获取学生列表失败')
          this.studentList = []
        }
      } else {
        this.studentList = []
      }
    },
    handleSelectionChange(val) {
      this.selectedStudents = val
    },
    getStatusText(status) {
      const statusMap = {
        0: '正常',
        1: '迟到',
        2: '早退',
        3: '旷课',
        null: '未记录'
      }
      return statusMap[status] || '未知'
    },
    getStatusType(status) {
      const typeMap = {
        0: 'success',
        1: 'warning',
        2: 'warning',
        3: 'danger',
        null: 'info'
      }
      return typeMap[status] || 'info'
    },
    handleBatchAttendance() {
      if (this.selectedStudents.length === 0) {
        this.$message.warning('请选择学生')
        return
      }
      this.batchDialogVisible = true
    },
    handleManualRecord() {
      this.manualForm = {
        userId: null,
        status: null,
        remark: ''
      }
      this.manualDialogVisible = true
    },
    recordSingle(student) {
      this.manualForm = {
        userId: student.id,
        status: null,
        remark: ''
      }
      this.manualDialogVisible = true
    },
    async submitBatchAttendance() {
      try {
        const params = {
          courseId: this.selectedCourse.id,
          userIds: this.selectedStudents.map(s => s.id),
          status: this.batchForm.status,
          remark: this.batchForm.remark
        }
        
        const res = await request.post('/attendance/batch', params)
        
        if (res.code === 200) {
          this.$message.success('批量考勤记录成功')
          this.batchDialogVisible = false
          // 刷新今日考勤状态
          await this.getTodayAttendanceStatus(this.selectedCourse.id)
        } else {
          this.$message.error(res.msg || '批量考勤记录失败')
        }
      } catch (error) {
        console.error('批量考勤记录失败:', error)
        this.$message.error('批量考勤记录失败')
      }
    },
    async submitManualRecord() {
      try {
        const params = {
          courseId: this.selectedCourse.id,
          userId: this.manualForm.userId,
          status: this.manualForm.status,
          remark: this.manualForm.remark
        }
        
        const res = await request.post('/attendance/record', params)
        
        if (res.code === 200) {
          this.$message.success('考勤记录成功')
          this.manualDialogVisible = false
          // 刷新今日考勤状态
          await this.getTodayAttendanceStatus(this.selectedCourse.id)
        } else {
          this.$message.error(res.msg || '考勤记录失败')
        }
      } catch (error) {
        console.error('考勤记录失败:', error)
        this.$message.error('考勤记录失败')
      }
    },
    // 获取今日考勤状态
    async getTodayAttendanceStatus(courseId) {
      try {
        if (!courseId || this.studentList.length === 0) return
        
        // 获取今天的日期
        const today = new Date()
        const todayStr = today.toISOString().split('T')[0]
        
        // 获取今日考勤记录
        const params = {
          courseId: courseId,
          startDate: todayStr,
          endDate: todayStr
        }
        
        const res = await request.get('/attendance/page', { params })
        
        if (res.code === 200) {
          const records = res.data.records || []
          
          // 更新学生考勤状态
          this.studentList.forEach(student => {
            const record = records.find(r => r.userId === student.id)
            if (record) {
              student.todayStatus = record.status
            }
          })
        } else {
          this.$message.warning(res.msg || '获取今日考勤状态失败')
        }
      } catch (error) {
        console.error('获取今日考勤状态失败:', error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.teacher-attendance-manage {
  padding: 20px;
  
  .operation-bar {
    margin-bottom: 20px;
  }

  .mobile-operation-buttons {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }

  .mobile-operation-buttons .el-button {
    margin-left: 0;
    margin-bottom: 8px;
    width: 100%;
    text-align: left;
  }

  .mobile-operation-buttons .el-button:last-child {
    margin-bottom: 0;
  }
}

@media screen and (max-width: 768px) {
  .demo-form-inline .el-form-item {
    display: block;
    margin-right: 0;
    margin-bottom: 10px;
    width: 100%;
  }

  .demo-form-inline .el-select {
    width: 100%;
  }

  .el-table {
    width: 100%;
    font-size: 12px;
  }
  
  .el-button {
    padding: 7px 10px;
    font-size: 12px;
  }
  
  .operation-bar {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }
}
</style> 